﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;

namespace AmorCanino.Web.Handlers
{
    public class ProfilePictureHandler : IHttpHandler
    {
        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            var uId = context.Request.QueryString["uid"].ToString();

            if (string.IsNullOrWhiteSpace(uId))
                throw new Exception();

            var db = new AmorCanino.Web.Models.AmorCaninoDBDataContext();
            var userProfileGuid = db.Profiles.Where(p => p.UserId == int.Parse(uId)).Select(s => s.PictureGuid).SingleOrDefault();

            string originalPicture = "emptyProfile.jpg";

            if (userProfileGuid.HasValue)
                originalPicture = userProfileGuid.Value.ToString() + ".jpg";

            string path = context.Server.MapPath(AmorCanino.Common.ConfigurationHandler.GetPuctirePath);
            path = Path.Combine(path, originalPicture);
            if (!System.IO.File.Exists(path))
                throw new Exception();

            var thumbnailer = new AmorCanino.Common.Thumbnail.ThumbnailCreation();
            thumbnailer.SetScalingOption(Common.Thumbnail.ScalingOptions.MaintainAspect);
            thumbnailer.MaxImageLength = 35;
            var thumbned = thumbnailer.CreateThumbnailImage(path);

            context.Response.Clear();
            context.Response.ContentType = "image/jpeg";
            thumbned.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
        }
    }
}